# encoding: utf-8

class RecommendSubject < ActiveRecord::Base
  has_many :item_recommends
  
  validates_presence_of :title
  validates_uniqueness_of :title  
  
  FLAGS = { 1 => '热门商品', 2 => '本周人气榜', 3 => '兜兜推荐', 4 => '标签', 5 => '点评', 6 => '滚动商品', 7 => '热搜标签' }
  
  { :hot_items => 1, :top_items => 2, :recommend_items => 3, :tags => 4, :ratings => 5, :scroll_items => 6, :hot_search => 7 }.each do |name, flag|
    scope name, :conditions => { :flag => flag }
  end
  
  scope :filter, lambda { |params|
    c, h = [], {}
    
    unless params[:id].blank?
      c << "id LIKE :id"
      h[:id] = "%#{params[:id]}%"
    end
    unless params[:title].blank?
      c << "title LIKE :title"
      h[:title] = "%#{params[:title]}%"
    end
    unless params[:flag].blank?
      c << "flag = :flag"
      h[:flag] = params[:flag].to_i
    end
    
    { :conditions => [c.join(' AND '), h] }
  }
  
  class << self
    
    def flag_options
      FLAGS.sort.inject([]){ |arr, obj| arr << obj.reverse }
    end
    
  end
  
  def to_s
    title
  end
  
  def display_flag
    FLAGS[flag]
  end
  
  def del
    update_attributes!(:status => -1)
  end
  
  def related_object
    case flag
    when 1..3 then Item
    when 4 then Tag
    when 5 then ItemRating
    end
  end

end
